package rpc_netty.Encoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.Service.RpcException;
import rpc_1.object.RpcRequest;
import rpc_1.object.RpcResponse;
import rpc_netty.Serializer.PackageType;
import rpc_netty.interfaces.CommonSerializer;
import java.util.List;

public class CommonDecoder extends ReplayingDecoder {
    private static final Logger logger= LoggerFactory.getLogger(CommonDecoder.class);
    private static final int MAGIC_NUMBER=0xCAFEBABE;


    @SneakyThrows
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magic=in.readInt();
        if (magic!=MAGIC_NUMBER) {
            logger.error("the magic number is wrong {}", magic);
            throw new RpcException("未识别的协议");
        }
        int packageCode=in.readInt();
        Class<?> packageClass;
        if (packageCode== PackageType.REQUEST_PACK.getCode()){
            packageClass= RpcRequest.class;
        }else if (packageCode==PackageType.RESPONSE_PACK.getCode()){
            packageClass= RpcResponse.class;
        }else {
            logger.info("wrong package type {}",packageCode);
            throw new RpcException("不识别的数据包");
        }
        int serializerCode=in.readInt();
        CommonSerializer deserializer = CommonSerializer.getByCode(serializerCode);
        logger.info("serializer type:"+deserializer.getCode());
        if (deserializer==null){
            logger.error("wrong deserializer {}",serializerCode);
            throw new RpcException("不识别的反序列化器");
        }
        int length=in.readInt();
        byte[] bytes=new byte[length];
        in.readBytes(bytes);
        Object pkg = deserializer.deserialize(bytes, packageClass);
        out.add(pkg);
    }

}
